import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../function/model/post_model.dart';
import '../../function/model/user_model.dart';
import '../../function/state/post_state.dart';
import '../../function/state/user_state.dart';
import '../../function/state/like_state.dart';
import '../../function/state/follow_state.dart';
import '../../function/state/comment_state.dart';
import '../../function/widgets/login_dialog_widget.dart';
import '../../function/widgets/report_dialog.dart';
import '../../function/widgets/comment_dialog_widget.dart';

/// 帖子详情页控制器
class PostDetailController extends GetxController {
  final PostState _postState = Get.find<PostState>();
  final UserState _userState = Get.find<UserState>();
  final LikeState _likeState = Get.find<LikeState>();
  final FollowState _followState = Get.find<FollowState>();
  final CommentState _commentState = Get.find<CommentState>();

  /// 获取用户状态（用于页面访问）
  UserState get userState => _userState;

  // 当前帖子
  final Rx<PostModel?> _currentPost = Rx<PostModel?>(null);

  // 关注按钮动画状态
  final RxDouble _followButtonScale = 1.0.obs;

  @override
  void onInit() {
    super.onInit();
    // 初始化页面数据
    _initializePageData();
  }

  /// 初始化页面数据
  void _initializePageData() {
    // 获取传递的帖子参数
    final arguments = Get.arguments;
    PostModel? post;

    if (arguments is PostModel) {
      // 直接传递的PostModel对象
      post = arguments;
    } else if (arguments is Map<String, dynamic> &&
        arguments.containsKey('postId')) {
      // 从轮播图传递的postId
      final postId = arguments['postId'] as String;
      post = _postState.getPostById(postId);
    }

    if (post != null) {
      _currentPost.value = post;
      _postState.setCurrentPost(post);
    }

    // 使用 addPostFrameCallback 延迟设置用户ID，避免在构建阶段调用 setState
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 只有在用户已登录时才设置用户ID
      if (_userState.isLoggedIn && _userState.currentUser != null) {
        _likeState.setCurrentUserId(_userState.currentUser!.id);
        _followState.setCurrentUserId(_userState.currentUser!.id);
        _commentState.setCurrentUserId(_userState.currentUser!.id);
      }
    });
  }

  /// 获取当前帖子
  PostModel? get currentPost => _currentPost.value;

  /// 获取帖子作者信息
  UserModel? get postAuthor {
    if (currentPost == null) return null;
    return _userState.getUserById(currentPost!.userId);
  }

  /// 获取用户头像
  String getUserAvatar(String userId) {
    final user = _userState.getUserById(userId);
    return user?.avatar ?? 'assets/images/avatar1.png';
  }

  /// 获取用户名
  String getUserName(String userId) {
    final user = _userState.getUserById(userId);
    return user?.nickname ?? user?.username ?? 'UnknownUser';
  }

  /// 获取用户签名
  String getUserSignature(String userId) {
    final user = _userState.getUserById(userId);
    return user?.signature ?? 'Plant lover and nature enthusiast';
  }

  /// 切换帖子点赞状态
  void togglePostLike() {
    if (currentPost == null) return;

    // 检查用户是否已登录
    if (!_userState.isLoggedIn) {
      // 显示登录提示
      Get.dialog(const LoginDialogWidget(), barrierDismissible: true);
      return;
    }

    // 确保用户ID已设置
    if (_likeState.currentUserId.isEmpty) {
      _likeState.setCurrentUserId(_userState.currentUser!.id);
    }

    // 用户已登录，根据点赞状态进行切换
    if (_likeState.isPostLiked(currentPost!.id)) {
      _likeState.unlikePost(currentPost!.id);
    } else {
      _likeState.likePost(currentPost!.id);
    }
  }

  /// 检查帖子是否被点赞
  bool isPostLiked() {
    if (currentPost == null) return false;
    // 只有登录用户才能点赞
    if (!_userState.isLoggedIn) {
      return false;
    }
    return _likeState.isPostLiked(currentPost!.id);
  }

  /// 获取帖子点赞数
  int getPostLikes() {
    if (currentPost == null) return 0;
    return _likeState.getPostLikeCount(currentPost!.id);
  }

  /// 切换关注状态
  void toggleFollow() {
    if (currentPost == null) return;

    // 检查用户是否已登录
    if (!_userState.isLoggedIn) {
      // 显示登录提示
      Get.dialog(const LoginDialogWidget(), barrierDismissible: true);
      return;
    }

    // 确保用户ID已设置
    if (_followState.currentUserId.isEmpty) {
      _followState.setCurrentUserId(_userState.currentUser!.id);
    }

    // 执行点击动画
    _animateFollowButton();

    // 用户已登录，根据关注状态进行切换
    if (_followState.isFollowing(currentPost!.userId)) {
      _followState.unfollowUser(currentPost!.userId);
    } else {
      _followState.followUser(currentPost!.userId);
    }
  }

  /// 关注按钮点击动画
  void _animateFollowButton() {
    // 缩小到0.8
    _followButtonScale.value = 0.8;

    // 延迟后放大到1.0
    Future.delayed(Duration(milliseconds: 100), () {
      _followButtonScale.value = 1.0;
    });
  }

  /// 获取关注按钮缩放值
  double get followButtonScale => _followButtonScale.value;

  /// 检查是否关注了帖子作者
  bool isFollowingAuthor() {
    if (currentPost == null) return false;
    // 只有登录用户才能关注
    if (!_userState.isLoggedIn) {
      return false;
    }
    return _followState.isFollowing(currentPost!.userId);
  }

  /// 举报帖子
  void reportPost() {
    if (currentPost == null) return;

    Get.dialog(
      ReportDialogWidget(
        onReportSubmitted: (reportType) {
          // 处理举报提交
          _handleReportSubmission(reportType);
        },
      ),
      barrierDismissible: true,
    );
  }

  /// 处理举报提交
  void _handleReportSubmission(String reportType) {
    if (currentPost == null) return;

    // 删除帖子
    _postState.deletePost(currentPost!.id);

    // 返回上一个页面
    Get.back();
  }

  /// 播放视频
  void playVideo() {
    if (currentPost == null ||
        currentPost!.resourceType != ResourceType.video) {
      return;
    }

    // 跳转到视频播放页面
    Get.toNamed('/video-player', arguments: currentPost);
  }

  /// 获取帖子评论数
  int getPostCommentCount() {
    if (currentPost == null) return 0;
    return _commentState.getPostCommentCount(currentPost!.id);
  }

  /// 显示评论弹窗
  void showCommentDialog() {
    if (currentPost == null) return;

    Get.bottomSheet(
      CommentDialogWidget(
        postId: currentPost!.id,
        onCommentAdded: () {
          // 评论添加后的回调
        },
      ),
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
    );
  }

  void navigateToUserProfile(String userId) {
    if (_userState.isLoggedIn &&
        _userState.currentUser != null &&
        _userState.currentUser!.id == userId) {
      return;
    } else {
      final user = _userState.getUserById(userId);
      if (user != null) {
        Get.toNamed('/other-profile', arguments: user);
      }
    }
  }
}
